package com.YCH.user.service.Impl;

import com.YCH.model.article.dtos.ArticleActionDto;
import com.YCH.model.article.dtos.ArticleInfoDto;
import com.YCH.model.article.pojos.TbArticle;
import com.YCH.model.article.pojos.TbArticleComment;
import com.YCH.model.article.pojos.TbUserLikeTopic;
import com.YCH.model.article.vos.ApShowArticle;
import com.YCH.model.article.vos.ArticleActionVo;
import com.YCH.model.article.vos.ArticleShowList;
import com.YCH.model.article.vos.LocationVo;
import com.YCH.model.common.dtos.ResponseResult;
import com.YCH.model.common.enums.AppHttpCodeEnum;
import com.YCH.model.mappers.app.*;
import com.YCH.model.user.dtos.UserLikeTopicDto;
import com.YCH.model.user.pojos.TbUser;
import com.YCH.model.user.pojos.TbUserFan;
import com.YCH.model.user.pojos.TbUserFollow;
import com.YCH.model.user.vo.UserInfoVo;
import com.YCH.model.user.vo.UserVo;
import com.YCH.user.service.UserCenterService;
import com.YCH.utils.common.ZipUtils;
import com.YCH.utils.threadlocal.AppThreadLocalUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;

@Service
@SuppressWarnings("all")
public class UserCenterServiceImpl implements UserCenterService {
    @Autowired
    private TbArticleCommentMapper tbArticleCommentMapper;
    @Autowired
    private TbUserFanMapper tbUserFanMapper;
    @Autowired
    private TbUserFollowMapper tbUserFollowMapper;
    @Autowired
    private TbUserLikeTopicMapper tbUserLikeTopicMapper;
    @Autowired
    private TbUserMapper tbUserMapper;
    @Autowired
    private TbLikesBehaviorMapper tbLikesBehaviorMapper;
    @Autowired
    private TbCollectionBehaviorMapper tbCollectionBehaviorMapper;
    @Autowired
    private TbArticleMapper tbArticleMapper;
    @Autowired
    private RestTemplate restTemplate;
//    @Autowired
//    private DiscoveryClient discoveryClient;

    Logger logger = LoggerFactory.getLogger(UserCenterServiceImpl.class);
    /**
     * 获取当前登录用户评论
     * @return
     */
    @Override
    public ResponseResult ObtainUserComment() {
        TbUser user = AppThreadLocalUtils.getUser();
        // 用户和用户id不能同时为空
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        Long userId = null;
        if (user != null) {
            userId = user.getId();
        }
        List<TbArticleComment> tbArticleComments = tbArticleCommentMapper.selectUserComment(userId);
        for(TbArticleComment tbArticleComment : tbArticleComments){
            tbArticleComment.setContent(ZipUtils.gunzip(tbArticleComment.getContent()));
        }
        return ResponseResult.okResult(tbArticleComments);
    }

    /**
     * 获取当前登录用户的收藏
     * @return
     */
    @Override
    public ResponseResult ObtainUserCollection(ArticleInfoDto dto) {
        // 获取用户信息
        TbUser user = AppThreadLocalUtils.getUser();
        // 判断用户是否存在
        if(user == null){
            return ResponseResult.errorResult(200,"用户未登录");
        }
        Long id = user.getId();
        // 1.查询收藏行为表，拿到当前登录用户的收藏文章id们（articleIds）
        List<Long> articleIds = tbCollectionBehaviorMapper.selectArticleIdByUserIdAndOperation(id, (short) 0);
        if(articleIds == null){
            return ResponseResult.okResult(0,"您还没有收藏哦");
        }
        // 2.根据articleIds查询当前登录用户收藏文章列表
        List<TbArticle> tbArticles = tbArticleMapper.loadArticleListByUserCollection(articleIds);
        // 3.封装到vo列表
        List<ApShowArticle> apShowArticleList = new ArrayList<>();
        // 设置点赞、收藏、查看、评论数量dto
        ArticleActionDto articleActionDto = new ArticleActionDto();
        articleActionDto.setType((short) 0);
        // 将结果集封装到vo
        for (TbArticle tbArticle:tbArticles){
            ApShowArticle apShowArticle = new ApShowArticle();
            apShowArticle.setCategoryId(tbArticle.getCategoryId());
            // 设置省市区
            LocationVo locationVo = new LocationVo();
            locationVo.setProvinceId(tbArticle.getProvinceId());
            locationVo.setCityId(tbArticle.getCityId());
            locationVo.setCountyId(tbArticle.getCountyId());
            apShowArticle.setLocation(locationVo);
            // 点赞、收藏、查看、评论数量、转发、阅读位置（未实现）
            articleActionDto.setArticleId(tbArticle.getId());
            // spring中同一个service中方法相互调用事务
             String url = "http://localhost:9003/api/v1/article/load_article_action";
            //获取eureka中注册的user-service实例列表
//            List<ServiceInstance> serviceInstanceList = discoveryClient.getInstances("service-article");
//            ServiceInstance serviceInstance = serviceInstanceList.get(0);
//            String url = "http://" + serviceInstance.getHost() + ":" + serviceInstance.getPort()
//                    + "/api/v1/article/load_article_action" + id;
            ResponseEntity<HashMap> hashMapResponseEntity1 = restTemplate.postForEntity(url, articleActionDto, HashMap.class);
            ArticleActionVo articleActionVo = new ArticleActionVo();
            LinkedHashMap data = (LinkedHashMap) hashMapResponseEntity1.getBody().get("data");
            try {
                articleActionVo.setCollectionCount(Integer.parseInt((String) data.get("collectionCount")));
                articleActionVo.setCommentCount(Integer.parseInt((String) data.get("commentCount")));
                articleActionVo.setViewCount(Integer.parseInt((String) data.get("viewCount")));
                articleActionVo.setFabulousCount(Integer.parseInt((String) data.get("fabulousCount")));
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }
            apShowArticle.setArticleOpeartor(articleActionVo);
            // 点赞、收藏、查看、评论数量、转发、阅读位置 配置（未实现）
            ArticleInfoDto articleInfoDto = new ArticleInfoDto();
            articleInfoDto.setArticleId(tbArticle.getId());
            articleInfoDto.setUserId(dto.getUserId());
            articleInfoDto.setAuthorId(tbArticle.getUser().getId());
             String url2 = "http://localhost:9003/api/v1/article/load_article_behavior";
//            String url2 = "http://" + serviceInstance.getHost() + ":" + serviceInstance.getPort()
//                    + "/api/v1/article/load_article_behavior" + id;
            ResponseEntity<HashMap> hashMapResponseEntity2 = restTemplate.postForEntity(url2, articleInfoDto, HashMap.class);
            LinkedHashMap data1 = (LinkedHashMap) hashMapResponseEntity2.getBody().get("data");
            HashMap<String,Boolean> hashMap = new HashMap<>();
            try {
                hashMap.put("isFollow", Boolean.valueOf((String) data1.get("isFollow")).booleanValue());
                hashMap.put("isLike", Boolean.valueOf((String) data1.get("isLike")).booleanValue());
                hashMap.put("isCollection", Boolean.valueOf((String) data1.get("isCollection")).booleanValue());
                hashMap.put("isUnlike", Boolean.valueOf((String) data1.get("isUnlike")).booleanValue());
                hashMap.put("isForward", Boolean.valueOf((String) data1.get("isForward")).booleanValue());
            } catch (Exception e) {
                e.printStackTrace();
            }
            apShowArticle.setArticleOperatorConfig(hashMap);
            // 时间
            apShowArticle.setCreatTime(tbArticle.getCreatTime());
            try{
                // 文章列表内容
                ArticleShowList articleShowList = new ArticleShowList();
                articleShowList.setArticleId(tbArticle.getId());
                articleShowList.setTitle(tbArticle.getTitle());
                articleShowList.setImage(tbArticle.getImage());
                articleShowList.setPartContent(tbArticle.getPartContent());
                articleShowList.setCustomTag(tbArticle.getTag());
                articleShowList.setTagName(tbArticle.getFlag().getTagName());
                articleShowList.setTagId(tbArticle.getFlag().getId());
                apShowArticle.setContent(articleShowList);
                // 设置用户性息
                UserVo userVo = new UserVo();
                userVo.setUserId((int) tbArticle.getUser().getId());
                userVo.setUserName(tbArticle.getUser().getUsername());
                userVo.setLV((int) tbArticle.getLv().getLV());
                userVo.setHeadimg(tbArticle.getUser().getHeadimg());
                userVo.setNick(tbArticle.getUser().getNick());
                userVo.setSign(tbArticle.getUser().getSign());
                userVo.setSex(tbArticle.getUser().getSex());
                apShowArticle.setUser(userVo);
            }catch (NullPointerException e){
                logger.error("展示文章列表中tagId或者UserId为空" + e.getStackTrace());
                continue;
            }
            apShowArticleList.add(apShowArticle);
        }
        return ResponseResult.okResult(apShowArticleList);
    }

    /**
     * 获取当前用户的粉丝
     * @return
     */
    @Override
    public ResponseResult ObtainUserFans() {
        // 获取用户信息
        TbUser user = AppThreadLocalUtils.getUser();
        // 判断用户是否存在
        if(user == null){
            return ResponseResult.errorResult(200,"用户未登录");
        }
        Long id = user.getId();
        List<TbUserFan> tbUserFans = tbUserFanMapper.selectUserFansByUserId(id);
        return ResponseResult.okResult(tbUserFans);
    }

    /**
     * 获取当前登录用户的关注人
     * @return
     */
    @Override
    public ResponseResult ObtainUserFollow() {
        // 获取用户信息
        TbUser user = AppThreadLocalUtils.getUser();
        // 判断用户是否存在
        if(user == null){
            return ResponseResult.errorResult(200,"用户未登录");
        }
        Long id = user.getId();
        List<TbUserFollow> tbUserFollows = tbUserFollowMapper.selectUserFollowByUserId(id);
        return ResponseResult.okResult(tbUserFollows);
    }

    /**
     * 获取当前登录用户的关注话题
     * @return
     */
    @Override
    public ResponseResult ObtainUserTopics() {
        // 获取用户信息
        TbUser user = AppThreadLocalUtils.getUser();
        // 判断用户是否存在
        if(user == null){
            return ResponseResult.errorResult(200,"用户未登录");
        }
        Long id = user.getId();
        List<TbUserLikeTopic> tbUserLikeTopics = tbUserLikeTopicMapper.selectUserLikeTopicByUserId(id, UserLikeTopicDto.Type.LIKE.getCode());
        return ResponseResult.okResult(tbUserLikeTopics);
    }

    /**
     * 获取当前登录用户信息
     * @return
     */
    @Override
    public ResponseResult ObtainUserInfo() {
        // 获取用户信息
        TbUser user = AppThreadLocalUtils.getUser();
        // 判断用户是否存在
        if(user == null){
            return ResponseResult.errorResult(200,"用户未登录");
        }
        Long id = user.getId();
        // 1.获取用户信息
        TbUser tbUser = tbUserMapper.selectLvByIdDetailed(id);
        if(tbUser == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        // 2.粉丝人数
        Integer userFansCount = tbUserFanMapper.selectCountByUserId(id);
        // 3.获取关注人数
        Integer userFollowCount = tbUserFollowMapper.selectCountByUserId(id);
        // 4.点赞数量
        Integer FabulousCount = tbLikesBehaviorMapper.selectAllArticleCountByUserId(id, (short) 0);
        UserInfoVo userInfoVo = new UserInfoVo();
        userInfoVo.setTbUser(tbUser);
        userInfoVo.setUserFansCount(userFansCount);
        userInfoVo.setUserFollowCount(userFollowCount);
        userInfoVo.setFabulousCount(FabulousCount);
        return ResponseResult.okResult(userInfoVo);
    }

    /**
     * 更改用户信息
     * @param tbUser
     * @return
     */
    @Override
    public ResponseResult updateUserInfo(TbUser tbUser) {
        // 获取用户信息
        TbUser user = AppThreadLocalUtils.getUser();
        // 判断用户是否存在
        if(user == null){
            return ResponseResult.errorResult(200,"用户未登录");
        }
        Long id = user.getId();
        // 1.获取用户信息
        TbUser User = tbUserMapper.selectLvByIdDetailed(id);
        if(User == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        tbUser.setId(User.getId());
        Integer update = tbUserMapper.update(tbUser);
        if(update >= 1){
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }else {
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
        }

    }

    /**
     * 获取用户昵称
     * @param nick
     * @return
     */
    @Override
    public ResponseResult ObtainUserNick(String nick) {
        if(nick.isEmpty()){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        TbUser user = tbUserMapper.selectNick(nick);
        if(user != null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST);
        }else {
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
    }
}
